package com.openx.cloud.server.autoconfigure.security.oauth2;

import com.openx.cloud.server.autoconfigure.security.SecurityInfo;
import com.openx.cloud.server.autoconfigure.security.SecurityConstants;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义AccessToken转换器
 *
 * @author yadu
 */
public class AccessTokenEnhancer extends TokenEnhancerChain {

    /**
     * 生成token
     *
     * @param accessToken
     * @param authentication
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(accessToken);
        final Map<String, Object> additionalInfo = new HashMap<>(8);
        Object principal = authentication.getPrincipal();
        if (principal != null) {
            if (principal instanceof SecurityInfo) {
                // 用户信息
                SecurityInfo baseUser = (SecurityInfo) principal;
                additionalInfo.put(SecurityConstants.OPEN_ID, baseUser.getId());
            }
            if (principal instanceof ClientDetails) {
                ClientDetails clientDetails = (ClientDetails) principal;
                additionalInfo.put(SecurityConstants.OPEN_ID, clientDetails.getAdditionalInformation().get("appId"));
            }
        }
        token.setAdditionalInformation(additionalInfo);
        return super.enhance(token, authentication);
    }
}
